﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using SelfService.Helpers;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using System.Threading.Tasks;
using System;
using WalkingTec.Mvvm.Core;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using SelfService.Model;

namespace SelfService.Controllers
{
    public partial class SysAppointmentController
    {
        [ActionDescription("查询科室列表")]
        [HttpPost("GetDepartmentList")]
        public async Task<Result<object>> GetDepartmentList()
        {
            var action = "查询科室列表";
            try
            {
                //调用HIS接口
                IAppointment service;
                try
                {
                    var scope = Wtm.ServiceProvider.CreateScope();
                    service = scope.ServiceProvider.GetRequiredService<IAppointment>();
                }
                catch (Exception)
                {
                    return new Result<object>()
                    {
                        Code = 1,
                        Message = "服务端没有启用该业务"
                    };
                }
                Request.EnableBuffering();
                Request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync();
                this.Logger($"{action}:{body}", ActionLogTypesEnum.Debug);
                var data = await service.GetDepartmentInfo(body);
                if (data.Code == 200)
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    return new Result<object>()
                    {
                        Data = data.Data
                    };
                }
                else
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    return new Result<object>
                    {
                        Code = 1,
                        Message = data.Message
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"{action}发生异常.异常信息: {JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return new Result<object>
                {
                    Code = 1,
                    Message = $"{action}异常"
                };
            }
        }

        [ActionDescription("查询医生列表")]
        [HttpPost("GetDoctorList")]
        public async Task<Result<object>> GetDoctorList()
        {
            var action = "查询医生列表";
            try
            {
                //调用HIS接口
                IAppointment service;
                try
                {
                    var scope = Wtm.ServiceProvider.CreateScope();
                    service = scope.ServiceProvider.GetRequiredService<IAppointment>();
                }
                catch (Exception)
                {
                    return new Result<object>()
                    {
                        Code = 1,
                        Message = "服务端没有启用该业务"
                    };
                }
                Request.EnableBuffering();
                Request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync();
                this.Logger($"{action}:{body}", ActionLogTypesEnum.Debug);
                var data = await service.GetDoctorInfo(body);
                if (data.Code == 200)
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    return new Result<object>()
                    {
                        Data = data.Data
                    };
                }
                else
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    return new Result<object>
                    {
                        Code = 1,
                        Message = data.Message
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"{action}发生异常.异常信息: {JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return new Result<object>
                {
                    Code = 1,
                    Message = $"{action}异常"
                };
            }
        }


        [ActionDescription("查询挂号费")]
        [HttpPost("GetRegFee")]
        public async Task<Result<object>> GetRegFee()
        {
            var action = "查询挂号费";
            try
            {
                //调用HIS接口
                IAppointment service;
                try
                {
                    var scope = Wtm.ServiceProvider.CreateScope();
                    service = scope.ServiceProvider.GetRequiredService<IAppointment>();
                }
                catch (Exception)
                {
                    return new Result<object>()
                    {
                        Code = 1,
                        Message = "服务端没有启用该业务"
                    };
                }
                Request.EnableBuffering();
                Request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync();
                this.Logger($"{action}:{body}", ActionLogTypesEnum.Debug);
                var data = await service.GetRegFee(body);
                if (data.Code == 200)
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    return new Result<object>()
                    {
                        Data = data.Data
                    };
                }
                else
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    return new Result<object>
                    {
                        Code = 1,
                        Message = $"{action}失败,{data.Message}"
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"{action}发生异常.异常信息: {JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return new Result<object>
                {
                    Code = 1,
                    Message = $"{action}异常"
                };
            }
        }
        
        
        [ActionDescription("预约挂号")]
        [HttpPost("AddOrder")]
        [ModelFilter]
        public async Task<Result<object>> AddOrder([FromBody] AddOrderRequest request)
        {
            var action = "现场挂号";
            try
            {
                SysPay pay = null;
                if (request.OrderType != "12")
                {
                    pay = await DC.Set<SysPay>()
                        .Where(e => e.OutOrderNo == request.OrderId)
                        .FirstOrDefaultAsync();
                    if (pay == null)
                    {
                        return new Result<object>
                        {
                            Code = 1,
                            Message = "支付信息不存在"
                        };
                    }
                    
                    if (pay.PayStatus != PayStatusEnum.支付成功)
                    {
                        return new Result<object>()
                        {
                            Code = 1,
                            Message = "未支付成功"
                        };
                    }
                    if (pay.Use != PayUseEnum.挂号)
                    {
                        return new Result<object>()
                        {
                            Code = 1,
                            Message = "无效的支付信息"
                        };
                    }
                    if (pay.UseStatus == UseStatusEnum.成功)
                    {
                        return new Result<object>()
                        {
                            Code = 1,
                            Message = "无效的支付信息"
                        };
                    }
                }
                //调用HIS接口
                IAppointment service;
                try
                {
                    var scope = Wtm.ServiceProvider.CreateScope();
                    service = scope.ServiceProvider.GetRequiredService<IAppointment>();
                }
                catch (Exception)
                {
                    return new Result<object>()
                    {
                        Code = 1,
                        Message = "服务端没有启用该业务"
                    };
                }
                Request.EnableBuffering();
                Request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync();
                this.Logger($"{action}:{body}", ActionLogTypesEnum.Debug);
                var data = await service.AddOrder(body);
                if (data.Code == 200)
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    return new Result<object>()
                    {
                        Data = data.Data
                    };
                }
                else
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    if (pay != null)
                    {
                        pay.UseStatus = UseStatusEnum.失败;
                        await DC.SaveChangesAsync();
                    }
                    return new Result<object>
                    {
                        Code = 1,
                        Message = $"{action}失败,{data.Message}"
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"{action}发生异常.异常信息: {JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return new Result<object>
                {
                    Code = 1,
                    Message = $"{action}异常"
                };
            }
        }

        [ActionDescription("支付")]
        [HttpPost("Pay")]
        public async Task<Result<object>> Pay([FromBody] AddOrderRequest request)
        {
            var action = "预约挂号";
            try
            {
                SysPay pay = null;
                if (request.OrderType != "12")
                {
                    pay = await DC.Set<SysPay>()
                        .Where(e => e.OutOrderNo == request.OrderId)
                        .FirstOrDefaultAsync();
                    if (pay == null)
                    {
                        return new Result<object>
                        {
                            Code = 1,
                            Message = "支付信息不存在"
                        };
                    }
                    
                    if (pay.PayStatus != PayStatusEnum.支付成功)
                    {
                        return new Result<object>()
                        {
                            Code = 1,
                            Message = "未支付成功"
                        };
                    }
                    if (pay.Use != PayUseEnum.挂号)
                    {
                        return new Result<object>()
                        {
                            Code = 1,
                            Message = "无效的支付信息"
                        };
                    }
                    if (pay.UseStatus == UseStatusEnum.成功)
                    {
                        return new Result<object>()
                        {
                            Code = 1,
                            Message = "无效的支付信息"
                        };
                    }
                }
                
                //调用HIS接口
                IAppointment service;
                try
                {
                    var scope = Wtm.ServiceProvider.CreateScope();
                    service = scope.ServiceProvider.GetRequiredService<IAppointment>();
                }
                catch (Exception)
                {
                    return new Result<object>()
                    {
                        Code = 1,
                        Message = "服务端没有启用该业务"
                    };
                }
                Request.EnableBuffering();
                Request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync();
                this.Logger($"{action}:{body}", ActionLogTypesEnum.Debug);
                var data = await service.Pay(body);
                if (data.Code == 200)
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    if (pay != null)
                    {
                        pay.UseStatus = UseStatusEnum.成功;
                        await DC.SaveChangesAsync();
                    }
                    return new Result<object>()
                    {
                        Data = data.Data
                    };
                }
                else
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    if (pay != null)
                    {
                        pay.UseStatus = UseStatusEnum.失败;
                        await DC.SaveChangesAsync();
                    }
                    return new Result<object>
                    {
                        Code = 1,
                        Message = $"{action}失败, {data?.Message}"
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"{action}发生异常.异常信息: {JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return new Result<object>
                {
                    Code = 1,
                    Message = $"{action}异常"
                };
            }
        }
        
        [ActionDescription("查询时段")]
        [HttpPost("GetTimeInfo")]
        public async Task<Result<object>> GetTimeInfo()
        {
            var action = "查询时段";
            try
            {
                //调用HIS接口
                IAppointment service;
                try
                {
                    var scope = Wtm.ServiceProvider.CreateScope();
                    service = scope.ServiceProvider.GetRequiredService<IAppointment>();
                }
                catch (Exception)
                {
                    return new Result<object>()
                    {
                        Code = 1,
                        Message = "服务端没有启用该业务"
                    };
                }
                Request.EnableBuffering();
                Request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync();
                this.Logger($"{action}:{body}", ActionLogTypesEnum.Debug);
                var data = await service.GetTimeInfo(body);
                if (data.Code == 200)
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    return new Result<object>()
                    {
                        Data = data.Data
                    };
                }
                else
                {
                    this.Logger($"{action}, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    return new Result<object>
                    {
                        Code = 1,
                        Message = $"{action}失败"
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"{action}发生异常.异常信息: {JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return new Result<object>
                {
                    Code = 1,
                    Message = $"{action}异常"
                };
            }
        }
    }

    public class AddOrderRequest
    {
        [NotEmpty]
        public string OrderId { get; set; }
        
        public string OrderType { get; set; }
    }
}
